<div class="dashboard-container">
    <!-- 添加用户信息卡片 -->
    <div class="user-info-card">
        <div class="user-avatar">
            <i class="fas fa-user"></i>
        </div>
        <div class="user-details">
            <div class="user-header">
                <h2>欢迎回来，<span id="welcomeUsername">用户</span>！</h2>
                <div class="account-info">
                    <p>
                        <span>账号：</span>
                        <span id="accountUsername"></span>
                    </p>
                    <p class="password-field">
                        <span>密码：</span>
                        <span id="accountPassword">********</span>
                        <i class="fas fa-eye password-toggle" onclick="togglePassword()"></i>
                        <button class="change-password-btn" onclick="showChangePasswordModal()">
                            <i class="fas fa-key"></i> 修改密码
                        </button>
                    </p>
                </div>
            </div>
            <div class="login-info">
                <p>本次登录时间：<span id="lastLoginTime">-</span></p>
                <p>最近刷新时间：<span id="currentLoginTime">-</span></p>
            </div>
        </div>
    </div>

    <!-- 添加修改密码模态框 -->
    <div id="changePasswordModal" class="modal">
        <div class="modal-content">
            <h3>修改密码</h3>
            <form id="changePasswordForm" onsubmit="return handleChangePassword(event)">
                <div class="form-group">
                    <label for="oldPassword">原密码：</label>
                    <input type="password" id="oldPassword" required>
                </div>
                <div class="form-group">
                    <label for="newPassword">新密码：</label>
                    <input type="password" id="newPassword" required>
                </div>
                <div class="form-group">
                    <label for="confirmPassword">确认密码：</label>
                    <input type="password" id="confirmPassword" required>
                </div>
                <div class="form-buttons">
                    <button type="button" onclick="closeChangePasswordModal()">取消</button>
                    <button type="submit">确认修改</button>
                </div>
            </form>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stats-card">
            <div class="stats-icon">
                <i class="fas fa-camera"></i>
            </div>
            <div class="stats-info">
                <h3>人脸检测</h3>
                <p id="detectCount">0</p>
                <small class="stats-trend" id="detectTrend"></small>
            </div>
        </div>
        <div class="stats-card">
            <div class="stats-icon">
                <i class="fas fa-map-marker"></i>
            </div>
            <div class="stats-info">
                <h3>特征点检测</h3>
                <p id="landmarksCount">0</p>
            </div>
        </div>
        <div class="stats-card">
            <div class="stats-icon">
                <i class="fas fa-exchange-alt"></i>
            </div>
            <div class="stats-info">
                <h3>面部对比</h3>
                <p id="compareCount">0</p>
            </div>
        </div>
        <div class="stats-card">
            <div class="stats-icon">
                <i class="fas fa-fingerprint"></i>
            </div>
            <div class="stats-info">
                <h3>特征编码</h3>
                <p id="encodingCount">0</p>
            </div>
        </div>
    </div>

    <div class="performance-section">
        <div class="performance-card">
            <div class="performance-header">
                <h3>系统性能</h3>
                <div class="refresh-controls">
                    <label class="auto-refresh">
                        <input type="checkbox" id="autoRefresh" checked>
                        自动刷新
                    </label>
                    <button class="refresh-button" onclick="refreshStats()">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
            <div class="performance-metrics">
                <div class="metric">
                    <span class="metric-label">平均响应时间</span>
                    <span class="metric-value" id="avgResponseTime">0ms</span>
                    <div class="metric-chart" id="responseTimeChart"></div>
                </div>
                <div class="metric">
                    <span class="metric-label">成功率</span>
                    <span class="metric-value" id="successRate">0%</span>
                    <div class="metric-chart" id="successRateChart"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="history-section">
        <div class="history-card">
            <div class="history-header">
                <h3>最近操作记录</h3>
                <div class="history-filter">
                    <select id="historyFilter">
                        <option value="all">全部</option>
                        <option value="success">成功</option>
                        <option value="error">失败</option>
                    </select>
                </div>
            </div>
            <div class="history-list-wrapper">
                <div class="history-list" id="usageHistory">
                    <!-- 历史记录将通过JavaScript动态插入 -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let refreshInterval;

// 初始化函数
function initDashboard() {
    refreshStats();
    setupAutoRefresh();
}

// 设置自动刷新
function setupAutoRefresh() {
    const autoRefreshCheckbox = document.getElementById('autoRefresh');
    autoRefreshCheckbox.addEventListener('change', function() {
        if (this.checked) {
            refreshInterval = setInterval(refreshStats, 10000); // 改为10秒刷新一次
        } else {
            clearInterval(refreshInterval);
        }
    });
    
    // 初始启动自动刷新
    if (autoRefreshCheckbox.checked) {
        refreshInterval = setInterval(refreshStats, 10000);
    }
}

// 刷新统计数据
async function refreshStats() {
    try {
        // 获取统计数据
        const statsResponse = await fetch('/api/stats', {
            headers: {
                'Authorization': localStorage.getItem('token')
            }
        });
        const statsData = await statsResponse.json();
        
        if (statsData.success) {
            updateDashboardStats(statsData.data);
        }

        // 获取使用记录
        const historyResponse = await fetch('/api/usage-history', {
            headers: {
                'Authorization': localStorage.getItem('token')
            }
        });
        const historyData = await historyResponse.json();
        
        if (historyData.success) {
            updateUsageHistory(historyData.data.history);
        }
    } catch (error) {
        console.error('刷新数据失败:', error);
    }
}

// 更新仪表盘统计数据
function updateDashboardStats(data) {
    const systemStats = data.system_stats;
    
    // 更新计数器
    document.getElementById('detectCount').textContent = systemStats.detect_count;
    document.getElementById('landmarksCount').textContent = systemStats.landmarks_count;
    document.getElementById('compareCount').textContent = systemStats.compare_count;
    document.getElementById('encodingCount').textContent = systemStats.encoding_count;
    
    // 更新性能指标
    document.getElementById('avgResponseTime').textContent = `${systemStats.avg_response_time}ms`;
    document.getElementById('successRate').textContent = `${systemStats.success_rate}%`;
    
    // 更新趋势指示器
    updateTrendIndicator('detectTrend', systemStats.detect_count);
    
    // 更新图表
    if (window.responseTimeChart) {
        updateChart(window.responseTimeChart, systemStats.avg_response_time);
    }
    if (window.successRateChart) {
        updateChart(window.successRateChart, systemStats.success_rate);
    }
}

// 更新趋势指示器
function updateTrendIndicator(elementId, currentValue) {
    const element = document.getElementById(elementId);
    if (!element) return;
    
    if (!element.dataset.lastValue) {
        element.dataset.lastValue = currentValue;
        return;
    }
    
    const lastValue = parseInt(element.dataset.lastValue);
    const trend = currentValue - lastValue;
    
    if (trend > 0) {
        element.innerHTML = `<i class="fas fa-arrow-up"></i> +${trend}`;
        element.className = 'stats-trend up';
    } else if (trend < 0) {
        element.innerHTML = `<i class="fas fa-arrow-down"></i> ${trend}`;
        element.className = 'stats-trend down';
    } else {
        element.innerHTML = `<i class="fas fa-minus"></i> 0`;
        element.className = 'stats-trend';
    }
    
    element.dataset.lastValue = currentValue;
}

// 更新图表
function updateChart(chart, newValue) {
    const now = new Date().toLocaleTimeString();
    
    chart.data.labels.push(now);
    chart.data.datasets[0].data.push(newValue);
    
    // 保持最近10个数据点
    if (chart.data.labels.length > 10) {
        chart.data.labels.shift();
        chart.data.datasets[0].data.shift();
    }
    
    chart.update();
}

// 更新使用记录
function updateUsageHistory(history) {
    const historyList = document.getElementById('usageHistory');
    const filter = document.getElementById('historyFilter').value;
    
    historyList.innerHTML = history
        .filter(record => filter === 'all' || 
                         (filter === 'success' && record.details.includes('成功')) ||
                         (filter === 'error' && record.details.includes('失败')))
        .map(record => `
            <div class="history-item ${record.details.includes('成功') ? 'success' : 'error'}">
                <div class="history-time">${record.time}</div>
                <div class="history-content">
                    <div class="history-function">${record.function}</div>
                    <div class="history-details">${record.details}</div>
                </div>
            </div>
        `).join('');
}

// 监听历史记录筛选器变化
document.getElementById('historyFilter').addEventListener('change', function() {
    const historyResponse = fetch('/api/usage-history', {
        headers: {
            'Authorization': localStorage.getItem('token')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateUsageHistory(data.data.history);
        }
    });
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initDashboard);
</script> 